#include "gamemanager.h"
#include <QThread>
#include <QVector2D>
#include "GameData/jsontranslator.h"
#include "ResourceManger/filemanager.h"
GameManager::GameManager()
{
    Init();
    curNode = NarrationTree::Instance().InitTree();
}

void GameManager::Init()
{
    Read();
    connect(&EventCenter::Instance(),&EventCenter::NextDialog,this,[=](bool noBranch){
        NextDialog(noBranch);
    });
    connect(&EventCenter::Instance(),&EventCenter::RenderInitOver,this,[=](){
        ShowNarration(curNode);
        //显示第一个节点
    });
    connect(&EventCenter::Instance(),&EventCenter::RunNarration,
            this,&GameManager::RunNarrationNode);
    connect(&EventCenter::Instance(),&EventCenter::DragImage,this,[=](QString &path){
        if(curNode)
        {
            curNode->image.push_back(new RenderTarget(path,QVector2D(0,0),10 - curNode->image.count(),1));
            ShowNarration(curNode);
        }
    });
    connect(&EventCenter::Instance(),&EventCenter::TextEdit,this,[=](QString& name,QString& text){
        curNode->text = text;
        curNode->name = name;
    });
    connect(&EventCenter::Instance(),&EventCenter::ChangeParticleSystem,this,[=](ParticleSystemInfo* info){
        if(!info)
        {
            curNode->effect = false;
            return;
        }
        curNode->effect = true;
        curNode->effectName = info->name;
    });
    //图鉴
    connect(&EventCenter::Instance(),&EventCenter::AddAlbum,[=](QString path)
    {
       if(!allAlbum.contains(path))
           allAlbum.push_back(path);
    });
    ReadAlbum();
    //数值
    connect(&EventCenter::Instance(),&EventCenter::RunRecord,[=](RecordItem* item){
        GameData::Instance().RefreshData(item);
        RunRecordFirstNode();
    });
    Save();
}

void GameManager::HandleNarrartionOption(NarrationNode *node)
{
    //在渲染画面上显示选项按钮
    if(!node)
    {
        return;
    }
    int count = 0;
    for(int i = 0; i < node->linkers.count(); i++)
    {
        if(!node->linkers[i]->branchOptionText.isEmpty())
        {
            render->GetOptionWidget()->ChangeBtnText(node->linkers[i]->branchOptionText,count);
            render->GetOptionWidget()->ChangeLinker(node->linkers[i],count);
            count++;
        }
    }
    render->GetOptionWidget()->Refresh(count);
}

void GameManager::NextDialog(bool noBranch)
{
    //获取下一个节点的id
    int nextId = -1;
    bool hasOption = false;
    for(int i = 0;i < curNode->linkers.count();i++)
    {
        if(!curNode->linkers[i]->branchOptionText.isEmpty())
        {
            hasOption = true;
            continue;
        }
        bool conditions = curNode->linkers[i]->AllConditionSatisfy();
        if(conditions)
        {
            curNode->linkers[i]->HandleAllAction();
            int b = curNode->linkers[i]->branchId;
            int c= curNode->linkers[i]->cycleId;
            if(NarrationTree::Instance().narrationTree[b])
            {
                nextId = b;
            }
            else if(NarrationTree::Instance().narrationTree[c])
            {
                nextId = c;
            }
        }
        if(NarrationTree::Instance().narrationTree[nextId])
            break;
    }
    if(nextId < 0 && curNode->childId < 0 && (noBranch || !hasOption))
    {
        emit EventCenter::Instance().GoToWidget("封面");
        Stop();
    }
    if(hasOption && !noBranch)
    {
        return;
    }
    int msecond = curNode->blackTime;
    if(msecond <= 0 || !curNode->black)
    {
        if(NarrationTree::Instance().narrationTree[nextId])
            RunNarration(NarrationTree::Instance().narrationTree[nextId]);
        else if(curNode->childId >= 0)
            RunNarration(NarrationTree::Instance().narrationTree[curNode->childId]);
        return;
    }
    emit EventCenter::Instance().Black(msecond);
    QTimer::singleShot(msecond,[=](){
        if(NarrationTree::Instance().narrationTree[nextId])
            RunNarration(NarrationTree::Instance().narrationTree[nextId]);
        else if(curNode->childId >= 0)
            RunNarration(NarrationTree::Instance().narrationTree[curNode->childId]);
    });
}

void GameManager::ReadAlbum()
{
    QJsonObject* ob = FileManager::Instance().ReadJsonFile(FileManager::Instance().albumPath);
    if(!ob)
    {
        return;
    }
    JsonTranslator jt;
    allAlbum = jt.StringVectorFromJson(ob);
}

void GameManager::CheckAlbum(NarrationNode *node)
{
    if(!record || !node)
        return;
    bool change = false;
    for(auto target:node->image)
    {
        QString path = target->GetPath();
        if(allAlbum.contains(path) && !record->album.contains(path))
        {
            record->album.push_back(path);
            change = true;
        }
    }
    if(change && record)
        emit EventCenter::Instance().RefreshAlbum(record->album);
}

void GameManager::RunRecordFirstNode()
{
    if(!record)
        return;
    int msecond = 1000;
    emit EventCenter::Instance().BlackLighter(msecond);
    if(NarrationTree::Instance().narrationTree[record->narrationId])
        RunNarration(NarrationTree::Instance().narrationTree[record->narrationId]);
}

void GameManager::RunNarrationNode(int id)
{
    RunNarration(NarrationTree::Instance().narrationTree[id]);
}

void GameManager::InitNode()
{

}

void GameManager::SetRecord(RecordItem *item)
{
    if(!item)
    {
        curNode = root;
    }
    record = item;
    if(NarrationTree::Instance().narrationTree[item->narrationId])
    {
        curNode = NarrationTree::Instance().narrationTree[item->narrationId];
    }
    emit EventCenter::Instance().RunRecord(item);
}

void GameManager::Save()
{
    QJsonObject ob;
    ob.insert("name",name);
    ob.insert("iconPath",iconPath);
    ob.insert("bgmPath",bgmPath);
    ob.insert("fullScreen",fullScreen);
    ob.insert("soundVolume",soundVolume);
    ob.insert("bgmVolume",bgmVolume);
    ob.insert("bgseVolume",bgseVolume);
    ob.insert("isGame",isGame);
    QString path = FileManager::Instance().gameManagerData;
    JsonTranslator jt;
    FileManager::Instance().Write(path,jt.Json2Byte(&ob));
}

void GameManager::Read()
{
    QString path = FileManager::Instance().gameManagerData;
    QJsonObject* ob = FileManager::Instance().ReadJsonFile(path);
    if(!ob)
        return;
    name = (*ob)["name"].toString();
    iconPath = (*ob)["iconPath"].toString();
    bgmPath = (*ob)["bgmPath"].toString();
    fullScreen = (*ob)["fullScreen"].toBool();
    soundVolume = (*ob)["soundVolume"].toInt();
    bgmVolume = (*ob)["bgmVolume"].toInt();
    bgseVolume = (*ob)["bgseVolume"].toInt();
    isGame = (*ob)["isGame"].toBool();
    emit EventCenter::Instance().ChangeWindowName("MyGame-" + name);
}

GameManager &GameManager::Instance()
{
    static GameManager instance;
    return instance;
}

GameManager::~GameManager()
{
    delete root;
    delete curNode;
}

void GameManager::RunNarration(NarrationNode *root)
{
    if(!root || !record)
        return;
    ShowNarration(root);
    InitSounds(root);
    //图鉴
    CheckAlbum(root);
    record->Refresh(root->id);
    record->Save();
    emit EventCenter::Instance().RefreshData();
}

void GameManager::Stop()
{
    SoundManager::Instance().Stop(SoundManager::BGM);
    SoundManager::Instance().Stop(SoundManager::BGSE);
    SoundManager::Instance().Stop(SoundManager::SOUND);

    record = nullptr;
    emit EventCenter::Instance().RunRecord(nullptr);
    emit EventCenter::Instance().RefreshData();
}

void GameManager::ShowNarration(NarrationNode *root)
{
    HandleNarrartionOption(root);
    curNode = root;
    if(!root)
    {
        qDebug()<<__FILE__<<__LINE__<<"剧情节点是空节点";
        return;
    }
    //台词
    render->SetDialog(root->text,root->name);
    //图
    render->ClearRenderList();
    for(int i = 0;i < root->image.count();i++)
    {
        RenderTarget* img = root->image.at(i);
        render->AddRenderTarget(img);
    }
    render->SetParticleDisabled(!root->effect);
}

void GameManager::InitSounds(NarrationNode *root)
{
    BGM* bgm = root->bgm;
    if(root->stopBgm)
    {
        SoundManager::Instance().Pause(SoundManager::BGM);
    }
    else if(bgm && FileManager::Instance().GetFileType(bgm->path) == FileManager::SOUND)
    {
        SoundManager::Instance().PlayBGM(bgm->path,bgm->loop);
    }
    else if(SoundManager::Instance().GetPlayer(SoundManager::BGM)->state() != QMediaPlayer::State::PlayingState)
    {
        //向上遍历父节点的BGM
        int id = root->parentId;
        while(NarrationTree::Instance().narrationTree.contains(id) &&
              NarrationTree::Instance().narrationTree[id])
        {
            NarrationNode* node = NarrationTree::Instance().narrationTree[id];
            if(node->stopBgm)
            {
                break;
            }else if(node->bgm)
            {
                SoundManager::Instance().PlayBGM(node->bgm->path,node->bgm->loop);
                break;
            }
            id = node->parentId;
        }
    }

    BGM* bgse = root->bgse;
    if(root->stopBgse)
    {
        SoundManager::Instance().Pause(SoundManager::BGSE);
    }
    else if(bgse)
    {
        SoundManager::Instance().PlayBGSE(bgse->path,bgse->loop);
    }
    if(root->soundPath.length() > 4)
        SoundManager::Instance().Play(root->soundPath);
}
